<template>
  <div>
    <el-switch v-model="isCustomDeliveryRange" active-color="#13ce66" inactive-color="#ff4949" active-value="1"
      inactive-value="0" @change="handleCustomDeliveryRange"></el-switch>
    <el-button type="text" @click="openCustomDeliveryRangeMap" v-if="isCustomDeliveryRange == 1">设置</el-button>
    <div class="font-12 font-color-9">不启用则以地理位置为中心按照默认配送范围计算配送区域</div>


    <el-dialog class="selectMap" title="自定义配送范围" :visible.sync="mapDialog" width="70%" :before-close="handleCloseMap"
      :close-on-press-escape="false" append-to-body>
      <div slot="title">
        <div class="pos-rel">
          <el-popover placement="top-start" width="300" trigger="hover" class="mar-l-20">
            <div>
              绘制：鼠标左键点击及移动即可绘制图形<br />
              结束绘制：鼠标左键双击即可结束绘制<br />
              中断：绘制或编辑过程中按下esc键可中断该过程<br />
            </div>
            <el-button type="text" slot="reference">使用说明</el-button>
          </el-popover>
          <div class="dialog-title">自定义配送范围</div>
        </div>
      </div>
      <div class="flex flex-between mar-b-20 pad-l-20 pad-r-20">
      </div>
      <div class="mapPage">
        <div id="toolControl">
          <div class="toolItem" id="delete" @click="handleDeleteEditor" title="删除" v-if="isShowDeleteButton"></div>
        </div>
        <div id="container" style=""></div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCloseMap">取 消</el-button>
        <el-button type="primary" @click="handleConfirmMap">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  // import {
  //   getToken
  // } from '@/utils/auth'

  import {
    getEnterpriseTencentAppKeyById
  } from '@/api/user/enterprise'
  export default {
    components: {},
    props: {
      // 是否自定义配送范围方法
      onHandleIsCustomDeliveryRange: Function,
      onHandleSetCustomDeliveryRange: Function, // 点击设置，打开自定义配送范围的时间，用于初始化地图，需要转入 地址和已画好的范围值
      onConfirm: Function,
      onCustomDeliveryRange: Function
    },
    data() {
      return {
        isCustomDeliveryRange: '0',
        isShowDeleteButton: false,
        mapDialog: false,
        lat: undefined,
        lng: undefined,
        mapObj: null,
        drawPaths: [],
        editor: undefined,
        defaultPaths: [],
        mapAppKey: ''
      }
    },
    mounted() {
      // 监听键盘按键事件
      this.$nextTick(function() {
        document.addEventListener('keyup', e => {
          // console.log('键盘事件：' + e.keyCode)
          // 此处填写你的业务逻辑即可
          if (e.keyCode === 27) {
            this.isShowDeleteButton = false
          } else if (e.keyCode === 46 || e.keyCode === 8) {
            this.handleDeleteEditor()
          }
        })
      })
    },
    watch: {

    },
    created() {
      getEnterpriseTencentAppKeyById(this.getEnterpriseId()).then(response => {
        if (response.isError) return
        this.mapAppKey = response.data
      })
    },
    methods: {

      // 选择是否自定义按钮事件
      handleCustomDeliveryRange(e) {
        this.onHandleIsCustomDeliveryRange(e)
      },
      setData(isCustomDeliveryRange) {
        this.isCustomDeliveryRange = isCustomDeliveryRange + ''
      },
      // 初始化是否自定义配送范围
      initIsCustomDeliveryRange(address, customType) {
        if (customType === '1') {
          if (!address) {
            this.isCustomDeliveryRange = '0'
            this.msgInfo('请先选择地区和填写完整的地址，才能自定义配送范围!')
            return false
          } else {
            this.isCustomDeliveryRange = customType
          }
        } else {
          this.isCustomDeliveryRange = customType
        }
        this.onCustomDeliveryRange(this.isCustomDeliveryRange)
      },
      // 确认选择
      handleConfirmMap() {
        var that = this
        var deliveryRangeList = []
        if (that.drawPaths && that.drawPaths.length > 0) {
          that.drawPaths.forEach(x => {
            var obj = {}
            obj.lng = x.lng
            obj.lat = x.lat
            obj.latFormat = x.lat
            obj.lngFormat = x.lng
            deliveryRangeList.push(obj)
          })
        }
        that.onConfirm(deliveryRangeList)
        that.mapDialog = false
      },
      // 关闭地图弹框
      handleCloseMap() {
        var that = this
        if (that.drawPaths.length > 0) {
          this.$confirm('只有点击确认，才会真正的保存数据，是否继续取消或关闭?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            that.mapDialog = false
          }).catch(() => {})
        } else {
          that.mapDialog = false
        }
      },
      // 删除选择的区域范围
      handleDeleteEditor() {
        if (this.isShowDeleteButton) {
          this.editor.delete()
          this.drawPaths = []
          this.editor.setActionMode(window.TMap.tools.constants.EDITOR_ACTION.DRAW)
          this.isShowDeleteButton = false
        }
      },
      // 打开地图弹框
      openCustomDeliveryRangeMap() {
        var that = this
        // 打开自定义配送范围的时间，用于初始化地图，需要转入 地址和已画好的范围值
        that.onHandleSetCustomDeliveryRange()
      },
      // 对外方法，传入地址和已选的配送范围数据
      initCustomDeliveryRange(cityName, address, deliveryRangeList) {
        console.log(address)
        console.log(deliveryRangeList)
        var that = this
        if (address === '' || address === undefined) {
          that.msgInfo('请先选择地区和填写地址，才能自定义配送范围!')
          return false
        }
        if (deliveryRangeList && deliveryRangeList.length > 0) {
          deliveryRangeList.forEach(x => {
            var obj = {}
            obj.lat = x.latFormat
            obj.lng = x.lngFormat
            that.defaultPaths.push(new window.TMap.LatLng(parseFloat(x.latFormat), parseFloat(x.lngFormat)))
            that.drawPaths.push(obj)
            if (that.lat === undefined) {
              that.lat = x.latFormat
              that.lng = x.lngFormat
            }
          })
        }
        // if (that.lat === undefined) {
        //   if (address === '' || address === undefined) {
        //     that.msgInfo('请先选择地区和填写地址，才能自定义配送范围!')
        //     return false
        //   }
        // }
        that.mapDialog = true
        if (that.mapObj) {
          return
        }
        if (!cityName) {
          cityName = '全国'
        }
        if (that.lat === undefined) {
          that.$jsonp('https://apis.map.qq.com/ws/place/v1/search', {
            key: this.mapAppKey,
            boundary: 'region(' + cityName + ')',
            keyword: address,
            output: 'jsonp'
          }).then(res => {
            console.log(res)
            if (res && res.data && res.data.length > 0) {
              var data = res.data[0]
              that.lat = data.location.lat
              that.lng = data.location.lng
            } else {
              that.lat = 39.908581
              that.lng = 116.397034
            }
            that.initMap()
          }).catch(err => {
            console.log(err)
            that.initMap()
          })
        } else {
          that.initMap()
        }
      },
      // 初始化地图
      initMap() {
        var that = this

        // 初始化地图
        that.$nextTick(() => {
          that.mapObj = new window.TMap.Map(document.getElementById('container'), {
            zoom: 14, // 设置地图缩放级别
            center: new window.TMap.LatLng(that.lat, that.lng) // 设置地图中心点坐标
          })
          that.initEditor()
        })
      },
      initEditor() {
        var that = this
        // 初始化几何图形及编辑器
        that.editor = new window.TMap.tools.GeometryEditor({
          map: that.mapObj, // 编辑器绑定的地图对象
          overlayList: [ // 可编辑图层
            {
              overlay: new window.TMap.MultiPolygon({
                map: that.mapObj,
                geometries: [{
                  paths: that.defaultPaths
                }]
              }),
              id: 'polygon'
            }
          ],
          actionMode: window.TMap.tools.constants.EDITOR_ACTION.DRAW, // 编辑器的工作模式
          activeOverlayId: 'polygon', // 激活图层
          selectable: true, // 开启点选功能
          snappable: true // 开启吸附
        })

        if (that.defaultPaths && that.defaultPaths.length > 0) {
          that.editor.setActionMode(window.TMap.tools.constants.EDITOR_ACTION.INTERACT)
        }
        // 监听绘制结束事件，获取绘制几何图形
        that.editor.on('draw_complete', (geometry) => {
          that.drawPaths = geometry.paths
          that.editor.setActionMode(window.TMap.tools.constants.EDITOR_ACTION.INTERACT)
        })
        that.editor.on('adjust_complete', geometry => {
          that.drawPaths = geometry.paths
        })
        that.editor.on('select', geometry => {
          that.isShowDeleteButton = true
        })
        that.markerLayer = new window.TMap.MultiMarker({
          id: 'marker-layer',
          map: that.mapObj
        })
      }
    }
  }
</script>

<style lang="less" scoped>
  .selectMap {
    display: flex;
    align-items: center;
    justify-content: center;

    /deep/.el-dialog {
      margin: 0 !important;
    }

    .s-result {
      height: 200px;
      overflow-y: scroll;
    }
  }

  .search-input {
    width: 96%;
    margin: 0 auto;
    display: block;

    /deep/ .el-input__inner {
      background-color: #f5f5f5;
    }
  }

  #toolControl {
    position: absolute;
    top: 135px;
    left: 50%;
    transform: translate(-50%);
    z-index: 1001;
  }

  .toolItem {
    width: 30px;
    height: 30px;
    float: left;
    margin: 1px;
    padding: 4px;
    border-radius: 3px;
    background-size: 30px 30px;
    background-repeat: no-repeat;
    box-shadow: 0 1px 2px 0 #E4E7EF;
    background-color: #ffffff;
    border: 1px solid #ffffff;
  }

  .toolItem:hover {
    border-color: #789CFF;
  }

  #delete {
    background-image: url('https://mapapi.qq.com/web/lbs/javascriptGL/demo/img/delete.png');
  }

  .dialog-title {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    font-size: 18px;
  }
</style>
